from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from rest_framework import status
from rest_framework.decorators import api_view, action, parser_classes
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.pagination import PageNumberPagination
from rest_framework.parsers import JSONParser
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView

from rest_framework.viewsets import ModelViewSet

from users.models import User, Clazz
from users.serializers import UserSerializer, ClazzSerializer


#
# @api_view(["GET"])
# def list(request):
#     # 查询用户表中所有数据
#     # select_related可以优化查询一对应的数据
#     queryset = User.objects.select_related("clazz")
#     # 使用序列化器对 queryset进行序列化，many=True（如果要序列化多条数据，要传入 many=True）
#     serializers = UserFormSerializer(queryset, many=True)
#     # 获取序列化后的结果
#     data = serializers.data
#     return Response(data=serializers.data)
#
#
# @api_view(["POST"])
# def add(request):
#     # 使用序列化器接收页面参数
#     serializer = UserFormSerializer(data=request.data)
#     # 验证传入的数据是否合法
#     serializer.is_valid(raise_exception=True)
#     # 保存数据，返回保存后的模型对象
#     instance = serializer.save()
#     # 构建一个序列化器去除密码
#     serializer = UserSerializer(instance)
#     return Response(data=serializer.data)
#
#
# @api_view(["PUT"])
# def update(request, pk):
#     instance = User.objects.get(pk=pk)
#     # 传入的数据必须是JSON格式的数据
#     data = JSONParser().parse(request)
#     serializer = UserFormSerializer(instance=instance, data=data)
#     if serializer.is_valid():
#         # 修改数据
#         instance = serializer.save()
#         # 去除密码
#         serializer = UserSerializer(instance)
#         # 返回Json
#         return Response(data=serializer.data)
#     return Response(data=serializer.errors, status=400)
#
#
# @api_view(["GET"])
# def clazz(request, pk):
#     # 一查多prefetch_related
#     clazz = Clazz.objects.prefetch_related('users').get(pk=pk)
#     if clazz is None:
#         return JsonResponse(status=404, data={"error": "Clazz not found"})
#     serializer = ClazzSerializer(clazz)
#     return Response(data=serializer.data)
#
#
# @api_view(["DELETE"])
# def delete(request, pk=None):
#     instance = User.objects.get(pk=pk)
#     instance.delete()
#     return Response(data={}, status=200)


# class UserView(APIView):
#     def get(self, request, *args, **kwargs):
#         if "pk" in kwargs:
#             instance = User.objects.get(pk=kwargs["pk"])
#             serializer = UserSerializer(instance)
#             return JsonResponse(data=serializer, safe=False)
#         queryset = User.objects.select_related("clazz")
#         serializer = UserSerializer(queryset, many=True)
#         return Response(data=serializer.data)
#
#     def post(self, request, *args, **kwargs):
#         serializer = UserFormSerializer(data=request.data)
#         if serializer.is_valid():
#             serializer.save()
#             return JsonResponse(data=serializer.data, safe=False)
#         return Response(data=serializer.errors, status=400)
#
#     def put(self, request, pk):
#         instance = User.objects.get(pk=pk)
#         # 传入的数据必须是JSON格式的数据
#         serializer = UserFormSerializer(instance=instance, data=request.data)
#         if serializer.is_valid():
#             # 修改数据
#             instance = serializer.save()
#             # 去除密码
#             serializer = UserSerializer(instance)
#             # 返回Json
#             return Response(data=serializer.data)
#         return Response(data=serializer.errors, status=400)
#
#     def delete(self, request, pk):
#         User.objects.filter(pk=pk).delete()
#         return Response(status=204)


# class UserView(ModelViewSet):
#     queryset = User.objects.all()
#     serializer_class = UserSerializer
#
#
# class ClazzView(ModelViewSet):
#     queryset = Clazz.objects.all()
#     serializer_class = ClazzSerializer
#
#     pagination_class = PageNumberPagination
#     parser_classes.page_size_query_param = 'rows'
#     pagination_class.page_size = 10
#
#     @action(methods=['get'], url_path='get', url_name='get', detail=False)
#     def paginate(self, request, *args, **kwargs):
#         queryset = self.get_queryset()
#         page = self.paginate_queryset(queryset)
#         if page is not None:
#             serializer = self.get_serializer(page, many=True)
#             return self.get_paginated_response(serializer.data)
#         serializer = self.get_serializer(queryset, many=True)
#         return Response(data=serializer.data)


from django_drf.fengzhang import send_mail


class NoAuthView(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    permission_classes = [AllowAny]

    def create(self, request, *args, **kwargs):
        # 获取数据
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 验证用户是否被注册
        if User.objects.filter(username=serializer.validated_data['username']).exists():
            return Response({'status': False, 'message': "用户已被注册"}, status=status.HTTP_400_BAD_REQUEST)
        # 分离出clazz字段，因为企业用户不需要clazz
        clazz_id = serializer.validated_data.pop('clazz', None)
        # 区分账号类型并处理
        is_staff = serializer.validated_data['is_staff']
        user = self.perform_create(serializer)
        if is_staff:
            # 企业用户，clazz不需要，账号状态为已激活
            status_message = "注册成功"
        else:
            # 普通用户，clazz必须存在，账号状态为未激活
            if clazz_id is None:
                return Response({'status': False, 'message': '普通用户必须提供班级ID'},
                                status=status.HTTP_400_BAD_REQUEST)
            # 发送并激活邮件
            send_mail(request, user)
            serializer.validated_data['is_active'] = False
            status_message = '注册成功，请尽快前往邮箱激活账号'
        # 返回注册成功响应
        headers = self.get_success_headers(serializer.data)
        return Response({'status': True, 'message': status_message}, status=status.HTTP_201_CREATED, headers=headers)



